<template>
  <div class="contract-page">
    <div v-if="loading" class="loading">
      <el-loading :active="loading" />
    </div>
    <div v-else class="contract-container">
      <div class="contract-content">
        <h2>房源信息</h2>
        <div class="info-section">
          <div class="info-row">
            <span class="label">房源地址：</span>
            <span class="value">{{ contractData.house_address }}</span>
            <span class="label">房型：</span>
            <span class="value">{{ contractData.house_type }}</span>
          </div>
          <div class="info-row">
            <span class="label">面积：</span>
            <span class="value">{{ contractData.area }}m²</span>
          </div>
        </div>

        <h2>备注信息</h2>
        <div class="info-section">
          <div class="info-row">
            <span class="value">{{ contractData.remarks || '暂无备注' }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="actions">
          <el-button type="primary" @click="handlePayment">确认并支付</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { createAlipayOrder } from '@/http/api/payment'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const contractData = ref({})
const loading = ref(false)
const userStore = useUserStore()

// 获取合同数据
const fetchContractData = async () => {
  try {
    loading.value = true
    const response = await axios.get(`http://127.0.0.1:8000/users/contract/get/`, {
      params: {
        id: route.query.id
      },
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
    
    if (response.data.code === 200) {
      contractData.value = response.data.data
    } else if (response.data.code === 404) {
      ElMessage.error('未找到相关合同')
      router.push('/') // 合同不存在时返回首页
    } else {
      ElMessage.error(response.data.message || '获取合同数据失败')
    }
  } catch (error) {
    console.error('获取合同数据失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error('合同不存在或已被删除')
      router.push('/')
    } else {
      ElMessage.error('获取合同数据失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 添加支付处理函数
const handlePayment = async () => {
  try {
    // 检查用户ID
    const userId = localStorage.getItem('userid')
    if (!userId) {
      ElMessage.error('用户未登录')
      router.push('/login')
      return
    }

    // 生成订单号
    const now = new Date()
    const timestamp = now.getTime()
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
    const orderNumber = `ORDER${timestamp}${random}`

    // 创建支付订单
    const response = await createAlipayOrder({
      order_number: orderNumber,
      total_amount: contractData.value.total_amount,
      order_type: '房屋租赁',
      subject: '房屋租赁费用',
      body: `房屋租赁费用支付 - ${contractData.value.house_address}`,
      userid: parseInt(userId) // 确保传递数字类型的用户ID
    })

    if (response.code === 200) {
      // 在新窗口打开支付页面
      window.open(response.data.pay_url, '_blank')
    } else {
      ElMessage.error(response.message || '创建订单失败')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请重试')
  }
}

onMounted(() => {
  fetchContractData()
})
</script>

<style scoped>
.contract-page {
  padding: 20px;
}

.contract-container {
  max-width: 800px;
  margin: 0 auto;
}

.contract-content {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
}

.info-section {
  margin-bottom: 30px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.label {
  color: #666;
  margin-right: 10px;
  min-width: 80px;
}

.value {
  color: #333;
  margin-right: 30px;
}

.actions {
  margin-top: 30px;
  text-align: center;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}
</style>